package com.rpcdemo.netyyrpc;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * create by yongli on 2021-10-23 16:15
 * netty框架实现的rpc，在test文件中启动
 * 不使用spring框架
 */

public class Client {
    private final String host;
    private final int port;

    public Client(String host, int port) {
        this.port = port;
        this.host = host;
    }

    public static void main(String[] args) throws Exception {

        // 这算不算是电脑内部，程序间的通信方式？
        Client client = new Client("localhost", 8080);
        client.start();
    }

    public void start() throws Exception {
        // 到底这东西有什么用呢？
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host, port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new EchoClientChannelHandler());
                        }
                    });
            ChannelFuture future = b.connect().sync();
            future.channel().closeFuture().sync();
        } finally {
            // EventGroup是什么
            group.shutdownGracefully().sync();
        }
    }

}

